<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */

class appRain_Base_Modules_Toolbar extends appRain_Base_Objects
{
	private $_buttons = null;
	const BUTTON_PADDING = "btn";
	private $opts  = null;
    
	/**
	 * Generate List of buttons
	 *
	 * Function execute in a singleton pattern
	 */
	private function init_buttons()
	{
		if($this->__data)
		{
			foreach($this->__data as $key=>$value)
			{
				if(substr($key,0,3)==self::BUTTON_PADDING){
					$this->prepareHTML($key,$value);					
				}
			}
		}
	}

	private function prepareHTML($fx,$args)
	{
		$this->_buttons[] = $this->$fx($args);
	}

	private function btnsave($args=null)
	{
		return App::Helper('Html')->submitTag('Button[button_save]',
											  $this->__((isset($args['name']) ? $args['name'] : 'Save')),
											  Array('title'=>$this->__('Save Entry')));
	}

	private function btnsaveandupdate($args=null)
	{
		return App::Helper('Html')->submitTag('Button[button_save_and_update]',
											  $this->__((isset($args['name']) ? $args['name'] : 'Save and Continue')),
                                              Array('title'=>$this->__('Save and Continue')));
	}

	private function btndelete($args=null)
	{
		return App::Helper('Html')->submitTag('Button[button_delete]',
						      $this->__((isset($args['name']) ? $args['name'] : 'Delete')),
						      Array('title'=>$this->__('Delete'),'class'=>'_deletebtn'));
	}


	private function btnfilemanager($args=null)
	{
		return App::Helper('Html')->buttonTag('Button[filemanager]',
											  $this->__((isset($args['name']) ? $args['name'] : 'File Manager')),
											  Array('title'=>$this->__('File Manager'),"onclick"=>"var win = window.open('" . App::Helper('Config')->baseurl('/admin/filemanager') . "','Window1','menubar=no,width=860,height=750,toolbar=no,scrollbars=yes');win.focus()"));
	}

	private function btnback($args=null)
	{
		return App::load("Helper/Html")->buttonTag("Button[Back]",
												   $this->__((isset($args['name']) ? $args['name'] : "<< Back")),
												   array("onclick"=>"javascript:history.go(-1)"));
	}

	private function btntoggle($args=null)
	{
		return App::load("Helper/Html")->buttonTag("Button[Toggle]",
												   $this->__((isset($args['name']) ? $args['name'] : "Toggle")),
												   array("class"=>"view_hidden_content"));
	}

    private function BtnInformationSetViewSrcBox()
    {
        $args = func_get_args();
        $definition = app::__def()->getInformationSetDefinition($args[0]['type']);
        
        $categoryTypesarr = array();
        $key_arr = array();
        foreach( $definition['fields'] as $key => $val)
        {
            if( $val['type'] == 'categoryTag' )
            {
                $categoryTypesarr[$key] = $val['category_type'];
            }
            $key_arr[$key] = $this->__($val['title']);
        }
        
        $Config = $args[0]['config'];
        $src_key = $args[0]['src_key'];
        $src_cat = $args[0]['src_cat'];
        $src_field = $args[0]['src_field'];
                
        $htmlHelper = App::Helper('Html');
        $html  = $htmlHelper->getTag('form',array('method'=>'post','action' => $Config->baseurl("/information/manage/{$args[0]['type']}"),'class'=>'app_form'));
        $html .= $htmlHelper->getTag('div',array('class'=>'left'), App::load("Helper/Html")->inputTag("data[Search][src_key]",$src_key) . $htmlHelper->selectTag("data[Search][field]",$key_arr,$src_field) . App::categorySet()->GroupTag("data[Search][category]",$categoryTypesarr,$src_cat) . $htmlHelper->submitTag("data[Search][request]","Search"));
        $html .= $htmlHelper->getTag('/form');
        
        return $html;
    }

    private function btninformationsetexportbox()
    {
        $args = func_get_args();
        $Config = $args[0]['config'];
        $htmlHelper = App::Helper('Html');
        $html = "";
        $html  = $htmlHelper->get_tag('form',array('method'=>'post','action' => $Config->baseurl("/information/export/{$args[0]['type']}"),'class'=>'app_form'));
        $html .= $htmlHelper->get_tag('div',array('class'=>'right'),App::load("Helper/Html")->selectTag("data[Export][type]",Array('CSV'=>'CSV','XML'=>'XML'),'CSV',Array('off_blank'=>'Yes')) . App::load("Helper/Html")->submitTag("data[Export][request]","Export"));
        $html .= $htmlHelper->get_tag('/form');
        
        return $html;
    }

    private function isTop()
    {
        return ($this->getTitle()) ? true : false;
    }
    
    public function btnCustomHTML()
    {
        $args = func_get_args();
        return $args[0];
    }
    
    private function getWrappered($innerHtml)
    {
        switch($this->isTop())
		{
                case true:        
                                $html  = '<h2 class="tool_bar_header">' . $this->__($this->getTitle()) . '</h2>';
                                $html .= '<div class="tool_bar tool_bar_top">';
                                $html .=        '<div class="intermediate-gap">';
                                $html .=                $innerHtml;
                                $html .=        '</div>';
                                $html .= '</div>'; break;
                default :
                                $html  = '<div class="tool_bar tool_bar_bottom">';
                                $html .=        '<div class="intermediate-gap">';
                                $html .=                $innerHtml;
                                $html .=        '</div>';
                                $html .= '</div>'; break;
		}
        
        return $html;
    }

	private function renderHTML($html="")
	{
        if(is_array($this->_buttons))$html = implode(" ",$this->_buttons);
        
		return $this->getWrappered($html);
	}

	public function init_pre_callbacks()
	{
		$hookResource = App::Module('Hook')->getHookResouce('Toolbar','button_at_start');
        
        if(!empty($hookResource))
		{
			foreach($hookResource as $node)
			{
				if(($class=$node['resource'][0])!="" && ($method=$node['resource'][1])!="")
				{
					$this->_buttons[] = App::__obj($class)->$method($this->opts);
				}
			}
		}        
	}

	public function init_post_callbacks()
	{
		$hookResource = App::Module('Hook')->getHookResouce('Toolbar','button_at_end');
        
        if(!empty($hookResource))
		{
			foreach($hookResource as $node)
			{
				if(($class=$node['resource'][0])!="" && ($method=$node['resource'][1])!="")
				{
					$this->_buttons[] = App::__obj($class)->$method($this->opts);
				}
			}
		}
	}

	public function clear()
	{
		$this->__data = null;
		$this->_buttons = null;
	}

	public function render($opts)
	{
		$this->opts = $opts;
		$this->init_pre_callbacks();
		$this->init_buttons();
		$this->init_post_callbacks();
		echo $this->renderHTML();
		$this->clear();
	}
}
